<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\MenuRequest;
use App\Http\Controllers\Controller;

use App\Http\Model\Menu;
use Intervention\Image\Facades\Image;

class MenuController extends Controller
{
    //
    public function menuList(){
    	$menu = new Menu;
    	$menuInfo = $menu->get();
    	return view("admin.menu.menuList", ["menuInfo"=>$menuInfo]);
    }
    public function menuAdd(){
    	$menu = new Menu;
    	$menuInfo = $menu->get();
    	return view("admin.menu.menuAdd", ["menuInfo"=>$menuInfo]);
    }
    public function menuAddRes(MenuRequest $request){
    	$menu = new Menu;
    	$menu->name = $request->input("name");
        $active = $request->input("active") or 0;
        if($request->hasFile("pic")){
            $menu->img = $this->uploadPic($request);
        }
        if($active == "on"){
            $active = 1;
        }
        $menu->active = $active;
        $menu->info = $request->input("info") or "";
    	$menu->save();
    	return redirect('admin/menu-list')->with('success','菜单新增成功');
    }
    public function menuUpdate($id){
    	$menu = new Menu;
    	$menuInfo = $menu->find($id);
    	return view("admin.menu.menuUpdate", ["menuInfo"=>$menuInfo]);
    }
    public function menuUpdateRes(MenuRequest $request){
    	// dd($request->all());
    	$menu = new Menu;
        $active = $request->input("active") or 0;
    	$menuInfo = $menu->find($request->input("id"));
    	$menuInfo->name = $request->input("name");
        if($request->hasFile("pic")){
            @unlink("./upload".$menuInfo->img);
            $menuInfo->img = $this->uploadPic($request);
        }
        if($active == "on"){
            $active = 1;
        }
        $menuInfo->active = $active;
        $menuInfo->info = $request->input("info") or "";
    	$menuInfo->save();
    	return redirect('admin/menu-list')->with('success','菜单修改成功');
    }
    public function menuDelete(Request $request){
    	$id = $request->input("id");
    	$menu = new Menu;
    	$menu->destroy($id);
    	echo 1;die;
    }
    public function uploadPic($request){
        if($request->hasFile("pic")){
            $destinationPath = "./upload/banner/";
            $fileName = time().rand(100000,999999).'.'.$request->file("pic")->getClientOriginalExtension();
            Image::make($request->file("pic"))->fit(1000, 200)->save($destinationPath.$fileName);
            return "/banner/".$fileName;die;
        }
    }
}
